#ifndef __THREAD_POOL_H__
#define __THREAD_POOL_H__

#include <atomic>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>

class ThreadPool
{
  public:
    ThreadPool(const int threadNums = 4);
    ~ThreadPool();

    void addTask(std::function<void()>&&);

    void waitAll();

  private:
    void threadFun(const int id);

  private:
    std::vector<std::thread> threads;
    std::queue<std::function<void()>> tasks;
    std::mutex mtx;
    // 任务到达或者要求停止
    std::condition_variable cvTask;
    // 通知任务结束
    std::condition_variable cvFinish;
    std::atomic<bool> stop{false};
    std::atomic<int> pendingTasks{0};
};

#endif  //__THREAD_POOL_H__